<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3">
        <div class="left-side-box">
          <div class="left-title" onselectstart="return false">
            事项清单版本
            <svg-icon icon-class="version-add" width="16" height="16" @click="handleVersionAdd"
                      style="position: absolute; top: calc(50% - 8px); right: 10px"></svg-icon>
          </div>
          <div v-for="(ver, idx) in versionList" :key="ver.id" class="left-item" :class="{'selected': selectedVersion.version === ver.version}"
               @click="handleVersionSelect(ver)" onselectstart="return false">
            <div v-show="!ver.expireDate" class="active">生效</div>
            <div>
              <i class="el-icon-date"></i>
              {{ver.version}}
            </div>
            <el-popover placement="bottom">
              <div style="text-align: center; margin: 0; width: 60px">
                <el-button icon="el-icon-circle-check" size="mini" type="text" style="margin: 0" @click="handleVersionActive(idx)">生效</el-button>
                <el-button icon="el-icon-edit" size="mini" type="text" style="margin: 0" @click="handleVersionEdit(idx)">编辑</el-button>
                <el-button icon="el-icon-view" size="mini" type="text" style="margin: 0" @click="handleVersionDetail(idx)">详情</el-button>
                <el-button icon="el-icon-delete" size="mini" type="text" style="color: #F00; margin: 0" @click="handleVersionDel(idx)">删除</el-button>
              </div>
              <div class="cell-more" slot="reference" >
                <i class="el-icon-more"></i>
              </div>
            </el-popover>
          </div>
        </div>
      </el-col>
      <el-col :span="21">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="事项目录" prop="itemCatalog">
            <el-input
              v-model="queryParams.itemName"
              placeholder="请输入事项目录"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="事项状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择事项状态" clearable size="small">
              <el-option v-for="item in statusTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="企业名称" prop="itemName">
            <el-select v-model="queryParams.companyName" placeholder="请选择企业名称">
              <el-option label="全部" value=""/>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="queryParams.createTime"
                            placeholder="请选择创建时间"
                            size="small" style="width: 240px"
                            value-format="yyyy-MM-dd"
                            type="date"></el-date-picker>
          </el-form-item>
          <el-row>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">筛选</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleItemAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              @click="handleReport"
            >上报</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              size="mini"
              @click="handleBatchImport"
            >批量导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="itemList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键id" align="center" prop="id" />
          <el-table-column label="事项目录" align="center" prop="itemCatalog" />
          <el-table-column label="事项名称" align="center" prop="itemName" />
          <el-table-column label="事项编码" align="center" prop="itemCode" />
          <el-table-column label="公司名称" align="center" prop="companyName" />
          <el-table-column label="决策会议顺序" align="center" prop="mettingOrder" />
          <el-table-column label="经法律审核" align="center" prop="isLegalReview">
            <template slot-scope="scope">
              {{ scope.row.isLegalReview === '1' ? '是' : '否'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="当前状态" align="center" prop="status" :formatter="statusFormatter" />
          <el-table-column label="操作" align="center" class-name="small-padding" width="200px">
            <template slot-scope="scope">
              <svg-icon style="margin-right:8px; cursor:pointer;" icon-class="edit" @click="handleItemUpdate(scope.row)"></svg-icon>
              <svg-icon style="margin-right:8px; cursor:pointer;" icon-class="report" @click="handleItemReport(scope.row)"></svg-icon>
              <svg-icon style="margin-right:8px; cursor:pointer;" icon-class="revoke" @click="handleItemRevoke(scope.row)"></svg-icon>
              <svg-icon style="margin-right:8px; cursor:pointer;" icon-class="preview" @click="handleItemDetail(scope.row)"></svg-icon>
              <svg-icon style="margin-right:8px; cursor:pointer;" icon-class="delete" @click="handleItemDelete(scope.row)"></svg-icon>
              <svg-icon style="cursor: pointer;" icon-class="approval" @click="handleItemApproval(scope.row)"></svg-icon>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改 清单版本 对话框 -->
    <el-dialog :title="versionTitle" :visible.sync="versionOpen" width="640px" append-to-body @open="handleVersionClose">
      <div style="font-size: 16px; color: #14284A; padding: 30px 10px; font-weight: 700;">
        <svg-icon icon-class="company"></svg-icon>
        安徽省交通控股集团有限公司
      </div>
      <el-form ref="versionForm" :model="versionForm" :rules="versionRules" label-width="80px">
        <el-form-item label="清单版本" prop="itemVersionName">
          <el-input :disabled="!versionModify" v-model="versionForm.itemVersionName" placeholder="请输入清单版本名称" />
        </el-form-item>
        <el-form-item label="版本年限" prop="version">
          <el-date-picker :disabled="!versionModify"
            v-model="versionForm.version"
            type="year" format="yyyy" value-format="yyyy"
            placeholder="请选择版本年限">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="itemCode">
          <el-input :disabled="!versionModify" v-model="versionForm.description" type="textarea" placeholder="请输入事项编码" />
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload
            v-if="versionModify"
            class="upload-demo"
            drag multiple
            :action="uploadUrl"
            :on-success="handleVersionUpload"
            :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <div style="display: flex; flex-flow: column nowrap">
            <div v-for="(verFile, idx) in versionFileList" :key="idx">
              <div style="float: left">{{verFile.realName}}</div>
              <el-button type="text" style="color: #666666; float: right; margin:0 15px 0 0;" @click="handleVersionDelete(idx)">
                <svg-icon icon-class="delete"></svg-icon>
                删除
              </el-button>
              <el-button type="text" style="color: #666666; float: right; margin:0 15px 0 0;" @click="download(verFile.url)">
                <svg-icon icon-class="preview"></svg-icon>
                预览
              </el-button>
              <el-button type="text" style="color: #666666; float: right; margin:0 15px 0 0;" @click="download(verFile.url)">
                <svg-icon icon-class="file-download"></svg-icon>
                下载
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitVersionForm">确 定</el-button>
        <el-button @click="cancelVersion">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" style="margin-top: 15vh;" width="400px" @close="handleBatchClose">
      <div style="height: 20px;"></div>
      <el-upload
        ref="batchUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-success="handleBatchSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px; color: #1890FF;" @click="download('group1/M00/00/00/rBBqSV82ECKAR9bGAAAn1Wii5R003.xlsx')">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！只能导入一个文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchForm">导 入</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改 事项 对话框 -->
    <el-dialog :title="item.title" :visible.sync="item.open" width="620px" append-to-body @close="handleItemClose">
      <el-form ref="itemForm" :model="item.form" :rules="item.rules" label-width="110px" style="padding-top: 20px; height: 50vh">
        <el-form-item label="事项名称" prop="itemName">
          <el-input :disabled="!item.modify" v-model="item.form.itemName" type="textarea" placeholder="请输入事项名称" />
        </el-form-item>
        <el-form-item label="事项目录" prop="itemCatalog">
          <el-select :disabled="!item.modify" v-model="item.form.itemCatalog" placeholder="请选择事项目录" clearable size="small">
            <el-option
              v-for="catalog in itemCatalogOptions"
              :key="catalog.value"
              :label="catalog.label"
              :value="catalog.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="经法律审核" prop="isLegalReview">
          <el-radio-group :disabled="!item.modify" v-model="item.form.isLegalReview">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="决策会议顺序" prop="mettingOrder">
          <el-select :disabled="!item.modify" v-model="item.form.mettingOrderList" placeholder="请按顺序选择会议类型" multiple style="width: 100%">
            <el-option v-for="mf in meetingTypeOptions" :key="mf.label" :label="mf.label" :value="mf.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="item.modify" type="primary" @click="submitItemForm">确 定</el-button>
        <el-button @click="cancelItem">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addItem, delItem, exportItem, getItem, listItem, updateItem, importData} from "@/api/szyd/item";
  import { downloadFile } from "@/api/common";
  import {addVersion, listVersion, updateVersion} from "@/api/szyd/version";
  import {delVersion} from "../../../api/szyd/version";
  import {download} from "../../../utils/ruoyi";

  export default {
  name: "Item",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 事项清单列表 表格数据
      itemList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: undefined,
        status: '',
        companyName: '',
        createTime: undefined,
        itemVersionId: undefined,
      },
      // 文件上传借口
      uploadUrl: process.env.VUE_APP_BASE_API + '/szyd/upload',

      versionTitle: '',
      versionForm: {},
      versionOpen: false,
      versionModify: true,
      versionRules: {
        itemVersionName: [
          { required: true, message: "清单版本名称不能为空", trigger: "blur" }
        ],
        version: [
          { required: true, message: "清单版本年限不能为空", trigger: "blur" }
        ]
      },
      selectedVersion: {},
      versionList: [],
      versionFileList: [],

      // 清单版本
      version: {
        open: false,
        modify: true,
        title: '',
        form: {},
        rules: {
          itemVersionName: [
            { required: true, message: "清单版本名称不能为空", trigger: "blur" }
          ],
          version: [
            { required: true, message: "清单版本年限不能为空", trigger: "blur" }
          ]
        },
        selected: {},
        fileList: [],
        list: []
      },

      // 事项
      item: {
        open: false,
        modify: true,
        title: '',
        form: {},
        rules: {
          itemName: [
            { required: true, message: "请输入事项名称", trigger: "blur" }
          ],
          itemCatalog: [
            { required: true, message: "请选择事项目录", trigger: "blur" }
          ],
          isLegalReview: [
            { required: true, message: "请选择是否需要法律审核", trigger: "blur" }
          ],
          mettingOrder: [
            { required: false, message: "请按顺序选择会议类型", trigger: "blur" }
          ],
        }
      },

      // 批量导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "事项清单批量导入",
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/szyd/item/importData"
      },

      statusTypeOptions: [
          {
        'label': '全部',
        'value': ''
      }, {
        'label': '草稿',
        'value': 'draft'
      }, {
        'label': '审核中',
        'value': 'verify'
      }, {
        'label': '审核通过',
        'value': 'approved'
      }, {
        'label': '审核拒绝',
        'value': 'reject'
      }, {
        'label': '已上报',
        'value': 'reported'
      }],
      itemCatalogOptions: [
          {
        'label': '路线方针政策',
        'value': 'D01'
      }, {
        'label': '法律法规',
        'value': 'D02'
      }, {
        'label': '上级重要决定',
        'value': 'D03'
      }, {
        'label': '发展战略',
        'value': 'D04'
      }, {
        'label': '企业破产',
        'value': 'D05'
      }, {
        'label': '企业改制',
        'value': 'D06'
      }, {
        'label': '兼并重组',
        'value': 'D07'
      }, {
        'label': '资产调整',
        'value': 'D08'
      }, {
        'label': '产权转让',
        'value': 'D09'
      }, {
        'label': '对外投资',
        'value': 'D10'
      }, {
        'label': '利益调配',
        'value': 'D11'
      }, {
        'label': '机构调整',
        'value': 'D12'
      }, {
        'label': '党的建设重大决策',
        'value': 'D13'
      }, {
        'label': '安全稳定的重大决策',
        'value': 'D14'
      }, {
        'label': '其他重大决策',
        'value': 'D15'
      }],
      // 会议类型
      meetingTypeOptions: [
          {
          'id': 1,
          'label': '党委会',
        },{
          'id': 2,
          'label': '职代会',
        },{
          'id': 3,
          'label': '党组会',
        },{
          'id': 4,
          'label': '董事会',
        },{
          'id': 5,
          'label': '经理层办公会',
        },{
          'id': 6,
          'label': '股东会',
        },{
          'id': 7,
          'label': '党委（党组）会',
        },{
          'id': 8,
          'label': '其他',
        },
      ]
    };
  },
  created() {
    this.getVersionList()
    // this.getList();
  },
  methods: {
    statusFormatter(row) {
      let statusList = this.statusTypeOptions.filter(value => {
        return value.value === row.status
      })
      return statusList && statusList.length > 0 ? statusList[0]['label'] : ''
    },

    handleVersionSelect(version) {
      this.selectedVersion = version
      this.getList()
    },
    /** 查询 事项清单 列表 */
    getList() {
      this.loading = true;
      this.queryParams.itemVersionId = this.selectedVersion.id
      listItem(this.queryParams).then(response => {
        this.itemList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 添加事项清单版本 */
    handleVersionAdd() {
      this.versionTitle = '新增清单版本'
      this.versionModify = true
      this.versionOpen = true
    },
    handleVersionEdit(index) {
      let version = this.versionList[index]
      this.versionForm = version
      if (this.versionForm && this.versionForm.evidenceFile) {
        this.versionFileList = JSON.parse(this.versionForm.evidenceFile)
      }
      this.versionTitle = '修改清单版本'
      this.versionModify = true
      this.versionOpen = true
    },
    handleVersionActive(index) {
      let version = this.versionList[index]
    },
    handleVersionDetail(index) {
      let version = this.versionList[index]
      this.versionForm = version
      if (this.versionForm && this.versionForm.evidenceFile) {
        this.versionFileList = JSON.parse(this.versionForm.evidenceFile)
      }
      this.versionTitle = '清单版本详情'
      this.versionModify = false
      this.versionOpen = true
    },
    handleVersionDel(index) {
      let version = this.versionList[index]
      delVersion(version.id).then(res => {
        if (res.code === 200) {
          this.getVersionList()
        }
        this.msgSuccess(res.msg)
      }).catch(err => {
        this.msgError(err)
      })
    },
    handleVersionClose() {
    },
    handleVersionUpload(res, file, fileList) {
      console.log(res, file, fileList)
      let {code, realName, url} = res
      if (code === 200) {
        this.versionFileList.push({
          realName,
          url
        })
      }
    },
    handleVersionDelete(index) {
      this.versionFileList.splice(index, 1)
    },
    cancelVersion() {
      this.resetForm('versionForm')
      this.versionForm = {}
      this.versionFileList = []
      this.versionOpen = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submitVersionForm() {
      this.$refs['versionForm'].validate(valid => {
        if (valid) {
          console.log("submitVersionForm")
          this.versionForm.evidenceFile = JSON.stringify(this.versionFileList)
          if (this.versionForm.id) {
            updateVersion(this.versionForm).then(res => {
              this.msgSuccess("更新成功")
              this.cancelVersion()
              this.getVersionList()
            }).catch(err => {
              this.msgError(err)
            })
          } else {
            addVersion(this.versionForm).then(res => {
              this.msgSuccess("添加成功")
              this.cancelVersion()
            }).catch(err => {
              this.msgError(err)
            })
          }
        }
      })
    },
    getVersionList() {
      listVersion().then(res => {
        if (res && res.code === 200) {
          this.versionList = res.data
          if (res.data && res.data.length > 0) {
            this.selectedVersion = res.data[0]
            this.getList()
          }
        }else {
          this.msgError(res.msg)
        }
      }).catch(err => {
        this.msgError(err)
      })
    },

    // 打开 事项清单批量导入
    handleBatchImport() {
      this.upload.open = true
    },
    handleBatchClose() {
      this.$refs['batchUpload'].clearFiles()
    },
    handleBatchSuccess() {
      this.upload.open = false
    },
    // 事项清单批量导入
    submitBatchForm() {
      this.$refs['batchUpload'].submit()
    },
    // 取消事项清单批量导入
    cancelBatch() {
      this.upload.open = false
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !=1
      this.multiple = !selection.length
    },

    // 取消按钮
    cancelItem() {
      this.item.open = false
      this.resetItem()
    },
    // 表单重置
    resetItem() {
      this.item.form = {
        id: undefined,
        itemCatalog: undefined,
        itemName: undefined,
        itemCode: undefined,
        companyName: undefined,
        mettingOrder: undefined,
        mettingOrderList: [],
        isLegalReview: '0',
        itemListId: undefined,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      // this.resetForm("itemForm");
      // this.$refs['itemForm'].resetFields()
    },
    /** 新增按钮操作 */
    handleItemAdd() {
      this.resetItem();
      this.item.open = true;
      this.item.modify = true;
      this.item.title = "新增事项清单";
    },
    /** 事项清单弹窗关闭回调 */
    handleItemClose() {
      this.item.form = {}
    },
    /** 修改按钮操作 */
    handleItemUpdate(row) {
      this.resetItem();
      const id = row.id
      getItem(id).then(response => {
        this.item.form = response.data;
        this.item.form.mettingOrderList = response.data.mettingOrder ? response.data.mettingOrder.split(',') : []
        this.item.open = true;
        this.item.modify = true;
        this.item.title = "修改事项清单";
      });
    },
    /** 提交按钮 */
    submitItemForm: function() {
      this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.item.form.itemVersionId = this.selectedVersion.id
          this.item.form.mettingOrder = this.item.form.mettingOrderList.join(',')
          if (this.item.form.id) {
            updateItem(this.item.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.item.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addItem(this.item.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.item.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 上报 */
    handleItemReport(row) {

    },
    /** 撤回 */
    handleItemRevoke(row) {

    },
    handleItemDetail(row) {
      this.resetItem();
      getItem(row.id).then(response => {
        this.item.form = response.data;
        this.item.form.mettingOrderList = response.data.mettingOrder.split(',')
        this.item.open = true;
        this.item.modify = false;
        this.item.title = "事项清单详情";
      });
    },
    /** 删除按钮操作 */
    handleItemDelete(row) {
      const ids = row.id;
      this.$confirm('是否确认删除事项清单名称为"' + row.itemName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delItem(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 审批 */
    handleItemApproval(row) {

    },
    /** 上报 */
    handleReport() {

    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所选事项清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportItem(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style lang="scss" scoped>
  .left-side-box {
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    height: calc(100vh - 125px);
    background: white;
    text-align: center;
    border-radius: 5px;

    .left-title {
      position: relative;
      width: 100%;
      height: 50px;
      font-size: 14px;
      line-height: 50px;
      color: white;
      background-color: #374261;
      border-radius: 5px 5px 0 0
    }

    .left-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      width: 90%;
      height: 60px;
      padding: 0 20px;
      font-size: 12px;
      line-height: 40px;
      margin-top: 5px;
      cursor: pointer;
      border-radius: 4px;
      background: #F7F8FA;
      border: 1px solid #DAE1ED;

      .active {
        position: absolute;
        left: 0;
        top: 0;
        width: 44px;
        height: 18px;
        line-height: 18px;
        font-size: 12px;
        color: #FFFFFF;
        background: #6AB687;
        border-radius: 4px 3px 10px 0;
      }
    }

    .selected {
      background: #EBF5FF;
      border: 2px solid #5AACFF;
      border-radius: 4px;
    }

  }
</style>
